﻿Shader "Custom/TestShader22"
{
	Properties
	{
		_MainTex ("Texture", 2D) = "white" {}
        _FogDensity("FogDensity", float) = 1
        _FogColor("FogColor", color) = (1,1,1,1)
        _FogStart("FogStart", float) = 0
        _FogEnd("FogEnd", float) = 1

        _Noise("Noise", 2D) = "white"{}
    }

    SubShader
    {
        CGINCLUDE
        #include "UnityCG.cginc"

        sampler2D _MainTex;
        float4 _MainTex_TexelSize;
        float _FogDensity;
        fixed4 _FogColor;
        float _FogStart;
        float _FogEnd;
        
        float4x4 _FrustumCornersRay;
        sampler2D _CameraDepthTexture;

        sampler2D _Noise;

        struct v2f
        {
            float4 pos : SV_POSITION;
            float2 uv : TEXCOORD0;
            float2 uv_depth : TEXCOORD1;
            float4 interpolatedRay : TEXCOORD2;
        };

        v2f vert(appdata_img v)
        {
            v2f o;
            o.pos = UnityObjectToClipPos(v.vertex);
            o.uv = v.texcoord;
            o.uv_depth = v.texcoord;
#if UNITY_UV_STARTS_AT_TOP
            if (_MainTex_TexelSize.y < 0)
            {
                o.uv_depth.y = 1 - o.uv_depth.y;
            }
#endif

            int index = 0;
            if (o.uv_depth.x < 0.5 && o.uv_depth.y < 0.5)
            {
                index = 0;
            }
            else if (o.uv_depth.x > 0.5 && o.uv_depth.y < 0.5)
            {
                index = 1;
            }
            else if (o.uv_depth.x > 0.5 && o.uv_depth.y > 0.5)
            {
                index = 2;
            }
            else
            {
                index = 3;
            }
#if UNITY_UV_STARTS_AT_TOP
            if (_MainTex_TexelSize.y < 0)
            {
                index = 3 - index;
            }
#endif
            o.interpolatedRay = _FrustumCornersRay[index];
            return o;
        }
        
        fixed4 frag(v2f i) : SV_Target
        {
            float linearDepth = LinearEyeDepth(SAMPLE_DEPTH_TEXTURE(_CameraDepthTexture, i.uv_depth));
            float3 worldPos = _WorldSpaceCameraPos.xyz + linearDepth * i.interpolatedRay.xyz;
            
            float noise = tex2D(_Noise, i.uv + _Time.y * float2(0.05, 0.05)).r;

            float fogDensity = (_FogEnd - worldPos.y) / (_FogEnd - _FogStart);
            fogDensity = saturate(fogDensity * _FogDensity * (noise + 0.5));

            fixed4 finalColor = tex2D(_MainTex, i.uv);
            finalColor.rgb = lerp(finalColor, _FogColor.rgb, fogDensity);
            return finalColor;
        }
        ENDCG

        Pass
        {
            ZWrite Off
            Cull Off
            ZTest Always

            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            ENDCG
        }
	}
}
